package com.lry.basic.algorithm.loadbanlance;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class ConsistentHash {
    //服务器列表
    private static List<String> servers = new ArrayList();
    //虚拟节点
    private static TreeMap<Integer,String> VNode = new TreeMap();
    //为每一个真实节点加的虚拟节点个数
    private static int V_NODE = 160;
    static{
        servers.add("192.168.0.1");
        servers.add("192.168.0.2");
        servers.add("192.168.0.3");
        servers.add("192.168.0.4");
        //为每一个节点添加虚拟节点
        for(String ip:servers){
            for(int i=0;i<V_NODE;i++){
                VNode.put(getHash(ip+"VN"+i),ip);
            }
        }
    }

    private static String getServer(String clientIp){
        int hash = getHash(clientIp);
        //拿到比hash大的第一个节点
        Integer nodeIndex = VNode.tailMap(hash).firstKey();
        //节点不存在
        if(null==nodeIndex){
            //拿所有节点第一个
            nodeIndex = VNode.firstKey();
        }
        return VNode.get(nodeIndex);
    }

    private static int getHash(String str) {
        final int p = 16777619;
        int hash = (int) 2166136261L;
        for (int i = 0; i < str.length(); i++)
            hash = (hash ^ str.charAt(i)) * p;
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;
        if (hash < 0)
            hash = Math.abs(hash);
        return hash;
    }

    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            System.out.println(getServer("client" + i));
            System.out.println(getServer("client" + i));
            System.out.println(getServer("client" + i));

        }
    }
}
